#include <fstream>
#include "settings.h"
#include "../gui.text.h"
#include "../gui.menu.h"

using namespace TOB;

void TOB::UI_Settings::run() {
  UIMenu menu(0, config.offsetY + 1, config.offsetX, 0);
  UIText text(config.offsetX, config.offsetY + 1, 0, 0);
  UIWindow _header(0, 0, 0, 1);
  header = &_header;

  text.multiline = true;
  text.eventTab = [&]() {
    text.running = false;
  };

  lines = &text.lines;
  loadFile();
  text.printBlock();

  menu.insert(config.lang["back"], [&](){ menu.running = false; });

  // Edit config
  menu.insert(config.lang["edit"], [&](){ 
        text.focus(); 
        menu.showCursor(false);
      });

  menu.insert(config.lang["save"], [&](){
        saveFile();
      });

  menu.insert(config.lang["cancel"], [&](){
        loadFile();
        text.clear();
        text.x = text.y = text.scrollX = text.scrollY = 0;
        text.printBlock();
      });


  menu.focus();
}


void TOB::UI_Settings::loadFile() {
  std::ifstream handle(CONFIG);
  if(!handle.is_open()) { 
    return status(config.lang["setting-cant-read"]); 
  }
  std::string line;
  lines->clear();
  while(handle.good()) {
    getline(handle, line);  
    lines->push_back(CONVERT(line));
  }
  handle.close();
  status(config.lang["settings-read"]);
}


void TOB::UI_Settings::saveFile() {
  std::ofstream handle(CONFIG);
  if(!handle.is_open()) { 
    return status(config.lang["setting-cant-write"]); 
  }
  for(uint32 i = 0;; ++i) {
    handle << CONVERT(lines->at(i));
    if(i < lines->size() - 1) {
      handle << std::endl;
    } else {
      break;
    }
  }
  handle.close();
  status(config.lang["settings-written"]);
}


void TOB::UI_Settings::status(String &status) {
  header->setColor(Color::Title);
  header->setCursor(0, 0);
  header->clearLine();
  String title = config.lang["settings"] + status;
  header->putString(title);
}
